package com.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MapperUtils {
    private static InputStream as;
    private static SqlSessionFactoryBuilder builder;
    private static SqlSessionFactory factory;
    private static SqlSession session;

    public static SqlSession init() throws IOException {
        //加载配置文件
        as = Resources.getResourceAsStream("SqlMapConfig.xml");
        //获取SqlSessionFactoryBuilder工厂对象
        builder = new SqlSessionFactoryBuilder();
        factory= builder.build(as);
        //通过工厂对象生产Session
        session = factory.openSession();
        return session;
    }

    public static void close() throws IOException {
        //提交事务
        session.commit();
        //释放资源
        session.close();
        as.close();
    }
}
